/* 
 * Copyright (C) 2012 UTSChedule
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package utsc.apps.utschedule.ui;

import greendroid.widget.QuickAction;
import greendroid.widget.QuickActionBar;
import greendroid.widget.QuickActionWidget;
import greendroid.widget.QuickActionWidget.OnQuickActionClickListener;

import java.util.ArrayList;
import java.util.List;

import utsc.apps.utschedule.R;
import utsc.apps.utschedule.UTSCheduleApp;
import utsc.apps.utschedule.classes.Exam;
import utsc.apps.utschedule.classes.Timetable;
import utsc.apps.utschedule.ui.activities.ExamDetailActivity;
import utsc.apps.utschedule.ui.activities.ExamFormActivity;
import utsc.apps.utschedule.ui.activities.SyncExamTask;
import utsc.apps.utschedule.ui.activities.adapters.ExamListAdapter;
import utsc.apps.utschedule.ui.interfaces.OnSyncListener;
import utsc.apps.utschedule.ui.interfaces.TimetableActivity;
import utsc.apps.utschedule.util.TimetableHelper;
import utsc.apps.utschedule.util.database.DatabaseManager;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.app.SherlockListFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.commonsware.cwac.merge.MergeAdapter;

/**
 * The custome list fragment to display all the {@link Exam exams}.
 *
 */
public class ExamListFragment extends SherlockListFragment implements OnItemLongClickListener, OnQuickActionClickListener{

	private MergeAdapter _adapter = null;
	private ExamListAdapter _midtermAdapter = null;
	private ExamListAdapter _finalAdapter = null;
	private ArrayList<Exam> _midterms;
	private ArrayList<Exam> _finals;
	private boolean _updated=true;
	private QuickActionBar _quickActionBar;
	/**
	 * To keep track of position of the selected exam during long item click
	 */
	private int _selectedExamPos=-1;
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		getListView().setCacheColorHint(Color.TRANSPARENT);
		setEmptyText("No Courses Found!");
		_adapter = new MergeAdapter();
		if (setupExamLists()){
			//setup the adapters
			_quickActionBar=new QuickActionBar(getSherlockActivity());
			QuickAction _editAction=new QuickAction(getSherlockActivity(), R.drawable.ic_action_edit_alt, "Edit");
			QuickAction _deleteAction=new QuickAction(getSherlockActivity(), R.drawable.ic_action_delete_alt, "Delete");
			_quickActionBar.addQuickAction(_editAction);
			_quickActionBar.addQuickAction(_deleteAction);
			_quickActionBar.setOnQuickActionClickListener(this);
			
			_adapter.addView(buildLabel("MIDTERMS"));
			_midtermAdapter=new ExamListAdapter(getSherlockActivity(), R.layout.exam_list_item, _midterms, Exam.TYPE_MIDTERM);
			_adapter.addAdapter(_midtermAdapter);
			
			_adapter.addView(buildLabel("FINALS"));
			_finalAdapter=new ExamListAdapter(getSherlockActivity(), R.layout.exam_list_item, _finals, Exam.TYPE_FINAL);
			_adapter.addAdapter(_finalAdapter);
			
		}

		setListAdapter(_adapter);
		getListView().setOnItemLongClickListener(this);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		menu.add(Menu.NONE, R.id.sync, 1, R.string.lb_sync).setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM|MenuItem.SHOW_AS_ACTION_WITH_TEXT).setIcon(R.drawable.ic_action_refresh);
		super.onCreateOptionsMenu(menu, inflater);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.sync:
			SherlockFragmentActivity activity=getSherlockActivity();
			if (activity instanceof OnSyncListener<?>) {
				new SyncExamTask(activity, TimetableHelper.getCurrentTermString()).execute();
			}
			return true;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	
	@Override
	public void onResume() {
		super.onResume();
		if (!_updated) {
			refreshExams();
		}
	}
	
	public void refreshExams() {
		if (setupExamLists()) {
			if (_midtermAdapter!=null) {
				_midtermAdapter.set_exams(_midterms);
				_midtermAdapter.notifyDataSetChanged();
			}
			
			if (_finalAdapter!=null) {
				_finalAdapter.set_exams(_finals);
				_finalAdapter.notifyDataSetChanged();
			}
		}
	}
	
	/**
	 * Setup the exam lists (midterm/final).
	 * @return true if successful, otherwise, false
	 */
	private boolean setupExamLists() {
		UTSCheduleApp app=(UTSCheduleApp) getSherlockActivity().getApplication();
		Timetable timetable=app.get_currentActiveTimetable();
		if (timetable!=null) {
			DatabaseManager dbManager=DatabaseManager.getInstance(getSherlockActivity());
			//check the total count of valid courses (non-tutorials)
			if (dbManager.countCoursesWithoutTutorials(timetable.get_timetableID())>0) {
				//get the list of all exams
				List<Exam> exams=dbManager.getExamList(timetable.get_timetableID());
				if (_midterms!=null) {
					_midterms.clear();
				}else {
					_midterms=new ArrayList<Exam>();
				}
				
				if(_finals!=null){
					_finals.clear();
				}else {
					_finals=new ArrayList<Exam>();
				}
				//loop through the exam list and filter each item into its associated category
				if (exams!=null && !exams.isEmpty()) {
					for (Exam exam : exams) {
						if (exam.get_type()==Exam.TYPE_MIDTERM) {
							_midterms.add(exam);
						}else {
							_finals.add(exam);
						}
					}
				}
				return true;
			}
		}
		return false;
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode==SherlockFragmentActivity.RESULT_OK){
			_updated=false;
		}
	}
	
	@Override
	public void onListItemClick(ListView parent, View v, int position, long id) {
		final ExamListAdapter adapter=(ExamListAdapter) _adapter.getAdapter(position);
		Intent requestExamIntent=new Intent();
		final Exam exam=(Exam) _adapter.getItem(position);
		if (exam!=null) {
			requestExamIntent.setClass(getSherlockActivity(),ExamDetailActivity.class);
			requestExamIntent.putExtra("RequestCode", TimetableActivity.RESULT_UPDATE_EXAM);
			requestExamIntent.putExtra(Exam.COURSE, exam.get_course().get_courseID());
			requestExamIntent.putExtra(Exam.EXAMID, exam.get_examId());
			requestExamIntent.putExtra(Exam.EXPIRED, exam.is_expired());
			startActivityForResult(requestExamIntent, TimetableActivity.RESULT_UPDATE_EXAM);
		}else {
			int type=adapter.get_examType();
			requestExamIntent.setClass(getSherlockActivity(),ExamFormActivity.class);
			requestExamIntent.putExtra("RequestCode", TimetableActivity.RESULT_NEW_EXAM);
			requestExamIntent.putExtra(Exam.TYPE, type);
			startActivityForResult(requestExamIntent, TimetableActivity.RESULT_NEW_EXAM);	
		}
			
	}

	/**
	 * A helper method to setup the section header with the given header label.
	 * @param label
	 * @return
	 */
	private View buildLabel(String label) {
		TextView textView = (TextView) LayoutInflater.from(
				getSherlockActivity()).inflate(R.layout.exam_list_header, null);
		textView.setText(label);
		return (textView);
	}

	@Override
	public void onQuickActionClicked(QuickActionWidget widget, int position) {
		final Exam exam=(Exam) _adapter.getItem(_selectedExamPos);
		if (exam!=null) {
			if (position==0) {
				Intent updateExamIntent=exam.getObjectIntent();
	        	updateExamIntent.setClass(getSherlockActivity(), ExamFormActivity.class);
				updateExamIntent.putExtra("CourseExam", exam.get_course().get_courseID());
				updateExamIntent.putExtra("RequestCode", TimetableActivity.RESULT_UPDATE_EXAM);
				startActivityForResult(updateExamIntent, TimetableActivity.RESULT_UPDATE_EXAM);
			}else {
				DatabaseManager.getInstance(getSherlockActivity()).deleteExam(exam.get_examId());
				if (setupExamLists()) {
					if (_midtermAdapter!=null) {
						_midtermAdapter.set_exams(_midterms);
						_midtermAdapter.notifyDataSetChanged();
					}
					if (_finalAdapter!=null) {
						_finalAdapter.set_exams(_finals);
						_finalAdapter.notifyDataSetChanged();
					}
				}
				Toast.makeText(getSherlockActivity(), "The Exam is deleted sucessfully!", Toast.LENGTH_SHORT).show();
			}
		}
		widget.dismiss();
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position,
			long id) {
		final Exam exam=(Exam) _adapter.getItem(position);
		if (exam!=null) {
			_selectedExamPos=position;
			_quickActionBar.show(view);
		}
		
		return true;
	}

}
